package com.oj.interceptor;

import com.oj.entity.Privilege;
import com.oj.entity.User;
import com.oj.exception.OJException;
import com.oj.mapper.PrivilegeMapper;
import com.oj.service.UserService;
import com.oj.util.CodeMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class AdminInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    @Autowired
    private PrivilegeMapper privilegeMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        User user = userService.getUserBySession(request);
        if (user == null) {
            response.sendRedirect(request.getContextPath() + "/enter");
            return false;
        }

        if (privilegeMapper.query(user.getUsername(), "HEAD") != null) {
            return true;
        }

        if (privilegeMapper.query(user.getUsername(), "ADMIN") != null) {
            return true;
        }

        throw  new OJException(CodeMsg.ADMIN_NO_ACCESS);
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }
}